package category

import (
	"context"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/golang/protobuf/ptypes/empty"
	"go.uber.org/zap"
	"mxshop_api/goods-web/forms"
	"mxshop_api/goods-web/global"
	"mxshop_api/goods-web/proto"
	"mxshop_api/user-web/api"
	"net/http"
	"strconv"
)

func Delete(ctx *gin.Context) {

	//1 先查询出该分类下的所有子分类
	//2.将所有的分类全部删除
	id := ctx.Param("id")
	idInt, err := strconv.ParseInt(id, 10, 32)
	if err != nil {
		api.HandleValidatorError(ctx, err)
		return
	}
	r, err := global.SrvConn.GetSubCategory(context.Background(), &proto.CategoryListRequest{Id: int32(idInt)})
	if err != nil {
		api.HandlerGrpcToHttp(err, ctx)
		return
	}
	var ids []int32
	for _, category := range r.SubCategorys {
		ids = append(ids, category.Id)
	}
	ids = append(ids, int32(idInt))
	if len(ids) > 0 {
		for i := 0; i < len(ids); i++ {
			_, err = global.SrvConn.DeleteCategory(context.Background(), &proto.DeleteCategoryRequest{Id: ids[i]})
			if err != nil {
				zap.S().Errorw("删除分类失败：", err.Error(), " 分类ID: ", ids[i])
			}
		}
	}

	//3.将该分类下的所有商品逻辑删除	确定么？

	ctx.JSON(http.StatusOK, gin.H{
		"msg": "删除成功",
	})
}

func List(ctx *gin.Context) {

	list, err := global.SrvConn.GetAllCategorysList(context.Background(), &empty.Empty{})
	if err != nil {
		api.HandlerGrpcToHttp(err, ctx)
		return
	}
	data := map[string]interface{}{}
	err = json.Unmarshal([]byte(list.JsonData), &data)
	if err != nil {
		zap.S().Errorw("【List】查询【分类列表】失败：", err.Error())
	}
	ctx.JSON(http.StatusOK, data)
}

func Detail(ctx *gin.Context) {

	id := ctx.Param("id")
	idInt, err := strconv.ParseInt(id, 10, 32)
	if err != nil {
		api.HandleValidatorError(ctx, err)
		return
	}
	r, err := global.SrvConn.GetSubCategory(context.Background(), &proto.CategoryListRequest{Id: int32(idInt)})
	if err != nil {
		api.HandlerGrpcToHttp(err, ctx)
		return
	}
	var respMap map[string]interface{}
	var subCategorys []map[string]interface{}
	for _, category := range r.SubCategorys {
		subCategorys = append(subCategorys, map[string]interface{}{
			"id":              category.Id,
			"name":            category.Name,
			"level":           category.Level,
			"parent_category": category.ParentCategory,
			"is_tab":          category.IsTab,
		})
	}
	respMap["id"] = r.Info.Id
	respMap["name"] = r.Info.Name
	respMap["level"] = r.Info.Level
	respMap["parent_category"] = r.Info.ParentCategory
	respMap["is_tab"] = r.Info.IsTab
	respMap["sub_categorys"] = subCategorys
	ctx.JSON(http.StatusOK, respMap)
}

func New(ctx *gin.Context) {

	var categoryForm forms.CategoryForm
	if err := ctx.ShouldBind(&categoryForm); err != nil {
		api.HandleValidatorError(ctx, err)
		return
	}
	result, err := global.SrvConn.CreateCategory(context.Background(), &proto.CategoryInfoRequest{
		Name:           categoryForm.Name,
		ParentCategory: categoryForm.ParentCategory,
		Level:          categoryForm.Level,
		IsTab:          *categoryForm.IsTab,
	})
	if err != nil {
		api.HandlerGrpcToHttp(err, ctx)
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"id": result.Id,
	})
}

func Update(ctx *gin.Context) {

	var updateCategoryForm forms.UpdateCategoryForm
	err := ctx.ShouldBind(&updateCategoryForm)
	if err != nil {
		api.HandleValidatorError(ctx, err)
		return
	}
	id := ctx.Param("id")
	idInt, err := strconv.ParseInt(id, 10, 32)
	if err != nil {
		api.HandleValidatorError(ctx, err)
		return
	}
	_, err = global.SrvConn.UpdateCategory(context.Background(), &proto.CategoryInfoRequest{
		Id:    int32(idInt),
		Name:  updateCategoryForm.Name,
		IsTab: *updateCategoryForm.IsTab,
	})
	if err != nil {
		api.HandlerGrpcToHttp(err, ctx)
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"msg": "修改成功",
	})
}
